<?php
/**
 * 触发邮件监控管理模块
 */   
namespace app\controllers\marketing;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use app\models\marketing\MailAutoCreate;
use app\models\marketing\MailAutoCreateMonitor;
use app\models\marketing\MailTemplate;
use app\models\marketing\UserGoods;
use app\models\marketing\MailGroup;
use app\models\marketing\MonitorMessageGetter;
use app\models\marketing\SiteMonitorMessageGetter;
use app\models\marketing\MailAutoCreateExceptionMessage;
use app\components\TemplateMarket;
use app\components\EmailMarket;
use app\components\msgcenter\MsgCenter;

use yii\data\Pagination;
class TriggerMailMonitorManageController extends \app\base\Controller
{
    public $enableCsrfValidation = false;
    protected $errorCode = [403]; // 这两种类型的状态码则提示发送超限

    protected $channelInfo = [
        2  => 'emarsys',
        6  => 'emarsys_new',
        4  => 'cheet',
        5  => 'benchmark',
        9  => 'webpower'
    ];
    /*
     * 接收人用户信息列表
     */
    public function actionMsgGettersList()
    {
        
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
         // 查询网站相关的数据
        $formData = Yii::$app->request->$mothod();
        $formData['site_id'] = isset($formData['site_id']) ? $formData['site_id'] : 0;
         // 查询有触发邮件相关配置的网站
//        $mailAutoCreate = new MailAutoCreate();
//        $siteInfoHaveTriggerMail = $mailAutoCreate->getAllSiteHaveAutoCreate();
//        
//        $siteInfoHaveTriggerArr = [];
//        foreach ($siteInfoHaveTriggerMail as $siteInfoHaveTriggerMailVal) {
//            $siteInfoHaveTriggerArr[] = $siteInfoHaveTriggerMailVal['site_id'];
//        }
        
        // 当前用户所有有权限的站点
        $siteInfo = $curSiteUsersArr = $curSiteUsers = [];
        $siteInfo[0] = "--选择网站/平台--";
        $siteInfo_tmp = Yii::$app->authority->getMarketEmailAccessSite();
      
        if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
            foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                 
                $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
                
                
            }
        }
        $siteInfo[99] = 'EMP'; // 暂定EMP ID为99
        
        $formData['siteInfo'] = $siteInfo;
        
        // 获取可以配置的用户数据
        $monitorMesGetterModel = new MonitorMessageGetter;
        $userList = $monitorMesGetterModel->getAllUsers();
        
        
        // 获取所选站点的配置用户数据
        $SiteMonitorMesGetterModel = new SiteMonitorMessageGetter;
        if($formData['site_id']) {
            $curSiteData = $SiteMonitorMesGetterModel->getDataBySiteId($formData['site_id']);
            $curSiteUsers = $curSiteData ? $curSiteData['getter'] : '';
        }
        if($curSiteUsers) {
            $curSiteUsersArr = explode(',', $curSiteUsers);
        }
        
        $formData['userList'] = $userList;
        return $this->render('//marketing//trigger-mail-monitor-manage/message-getters-list',[
            'data' => $formData, 
            'selectedUserIds' => $curSiteUsersArr
        ]);
    }
    
    /*
     * 微信模板
     * @return string
     */
    public function actionViewWechart() {
        $id = Yii::$app->request->get('id');
        $monitorType = Yii::$app->request->get('monitor_type');
        $id = intval($id);
        $monitorType = intval($monitorType);
        if($id) {
            $mailAutoCreateExceptionMessage = new MailAutoCreateExceptionMessage();
            $data = $mailAutoCreateExceptionMessage->getExceptionMessageById($id);
            $data['template_type'] = '';
            if($data && isset($data['template_id']) && $data['template_id']) {
                $mailTemplateModel = new MailTemplate;
                $mailTemplateData = $mailTemplateModel->getTemplateTypeById($data['template_id']);
                
                if($mailTemplateData) {
                    $data['template_type'] = $mailTemplateData['template_type_name'];
                }
            }
            $site = new \app\components\Site();
            $data['site_name'] = $site->getSiteShortNameById($data['site_id']);
            $data['monitorType'] = $monitorType;
            if($data['exception_type'] == 2) {// 发送异常
                $data['title'] = 'EMP营销邮件,'.$data['site_name'].' '.($data['template_type'] ? $data['template_type'] : '').'推送为0,导致EMP未发送邮件';
                $data['exceptionRerson'] = '网站推送为0,导致EMP未发送邮件';
            } else if ($data['exception_type'] == 1) {// 推送异常
                if($monitorType == 1) { // 推数过期
                    $data['title'] = 'EMP营销邮件,'.$data['site_name'].' '.($data['template_type'] ? $data['template_type'] : '').'推送过期,过期数'.$data['expire_user_count'].'个';
                    $data['exceptionRerson'] = '推送过期,过期数'.$data['expire_user_count'].'个';
                    $data['effective_nums'] = $data['push_user_count'] - $data['expire_user_count'];
                } else if($monitorType == 2) { // 推数过少
                    
                    // 低于均值的百分比
                    if (!empty($data['threshold_nums'])) {
                        $lessThanThresholdPercent = number_format((($data['threshold_nums']-$data['push_user_count']) / $data['threshold_nums']) * 100,2);
                    } else {
                        $lessThanThresholdPercent = 0;
                    }
                    $data['title'] = 'EMP营销邮件,'.$data['site_name'].' '.($data['template_type'] ? $data['template_type'] : '').'推送过少,低于均值'.$lessThanThresholdPercent.'%';
                    $data['exceptionRerson'] = '推送量过少,低于均值'.$lessThanThresholdPercent.'%';
                } else if($monitorType == 3) { // 推送过多
                    
                    // 高于均值的百分比
                    if (!empty($data['threshold_nums'])) {
                        $moreThanThresholdPercent = number_format((($data['push_user_count'] - $data['threshold_nums']) / $data['threshold_nums']) * 100,2);
                    } else {
                        $moreThanThresholdPercent = 0;
                    }
                    $data['title'] = 'EMP营销邮件,'.$data['site_name'].' '.($data['template_type'] ? $data['template_type'] : '').'推送过多,高于均值'.$moreThanThresholdPercent.'%';
                    $data['exceptionRerson'] = '推送量过多,高于均值'.$moreThanThresholdPercent.'%';
                }
                
            }
            
            return $this->render('//marketing//trigger-mail-monitor-manage/wechart-detail',[
                'data' => $data
            ]);
        }
    }
    
    /*
     * 发送过程监控
     * @return string
     */
    public function actionSendProcessMonitor() {
   
        $data = [];
        $siteInfo = [];
        $defaultPageSize = 20;
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
         // 查询网站相关的数据
        $formData = Yii::$app->request->$mothod();
        // 当前用户所有有权限的站点
        $siteInfoTmp = Yii::$app->authority->getMarketEmailAccessSite();
        $siteInfo[0] = '全部';
        if (isset($siteInfoTmp) && is_array($siteInfoTmp)) {
            foreach ($siteInfoTmp as $siteInfoTmpK => $iteInfoTmpV) {
                $siteInfo[$iteInfoTmpV['site_id']] = $iteInfoTmpV['name'];
            }
        }
        if (sizeof($siteInfo) < 2) {
            exit('你好，你没有任何网站的相关权限');
        }
        
        
        $formData['siteInfo'] = $siteInfo;
        
        // 发送方式
        if (empty($formData['sendtype'])) {
            $formData['sendtype'] = -1;
        }
        
        // 默认的时间数据
        if (!empty($formData['reservation_time'])){
            $reservationTimeArr = explode(' - ',$formData['reservation_time']);
            $formData['startTime'] = $reservationTimeArr[0];
            $formData['endTime'] = $reservationTimeArr[1];
        }
        
        // 当前时间 
        $curTime = \yii::$app->bjTime->time();
        $timeYearMonthStart = \yii::$app->bjTime->date('Y-m-d',$curTime-30*24*60*60);
        $timeYearMonthCurrent = \yii::$app->bjTime->date('Y-m-d',$curTime);
        $formData['startTime'] = !empty($formData['startTime']) ? $formData['startTime'] : $timeYearMonthStart;
        $formData['endTime'] = !empty($formData['endTime']) ? $formData['endTime'] : $timeYearMonthCurrent;
        // 当前搜索哪个网站的用户信息
        $formData['site_id'] = isset($formData['site_id']) ? $formData['site_id'] : array_keys($siteInfo)[0];
        
        // 判断有没有当前网站的相关权限
        if ($formData['site_id']) {
            $flag = Yii::$app->authority->judgeMarketEmailHaveSite($formData['site_id']);
            if (!$flag) {
                 $this->sysMsg('警告', '你的账号没有权限!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
            }
        } 
        
        // 当前分组状态
        $formData['state'] = isset($formData['state']) ? intval($formData['state']) : -1;
        
        // 分组id或者分组名称
        $formData['group_info'] = isset($formData['group_info']) ? trim($formData['group_info']) : "";
        // 获取邮件类型
        $TemplateMarket = new TemplateMarket();
         if (!empty($formData['site_id'])) {
            
            $templateTypeArr = $TemplateMarket->getTemplateType($formData['site_id']);
        } else {
            $templateTypeArr = $TemplateMarket->getTemplateType();
        }
       // $templateTypeArr = $TemplateMarket->getTemplateType();
        $templateTypeArrInfo[0] = "全部";
        if (isset($templateTypeArr) && is_array($templateTypeArr)) {
            foreach ($templateTypeArr as $templateTypeArrK => $templateTypeArrV) {
                $templateTypeArrInfo[$templateTypeArrV['id']] = $templateTypeArrV['template_type_name']; 
            } 
            $formData['tempType'] = $templateTypeArrInfo;
        }
        $formData['temp_type_id'] = isset($formData['temp_type_id']) ? intval($formData['temp_type_id']) : 0;
        
        // 分页参数相关
        $page = Yii::$app->request->$mothod('page') ? Yii::$app->request->$mothod('page') : 1;
        $pageSize = Yii::$app->request->$mothod('pagesize') ? Yii::$app->request->$mothod('pagesize') : $defaultPageSize;
        $formData['page'] = $page;
        $formData['pageSize'] = $pageSize;
        
        // 获取分组信息
        $groupModel = new \app\models\marketing\MailGroup();
        $groupInfo = $groupModel->getExceptionGroupList($formData);
        
        // 获取当前查询的所有分组id
        $allgroupIdArr = [];
        $allgroupIdStr = "";
        
        // 保存每个分组的
        $allGroupInfoStat = [];
        $allGroupInfoStatDeal = [];
        foreach ($groupInfo['groupList'] as $groupListK => $groupListV) {
            $allgroupIdArr[] = $groupListV['group_id'];
        }
        $allgroupIdStr = join(',',$allgroupIdArr);
      
        if ($allgroupIdStr) {
            // 查询当前这些分组的统计信息数量和总的发送数量（打开数，点击数，发送成功数，失败数，总发送数）
            $allGroupInfoStatSql = " select * from mail_group_email_type_statistics where gid in ({$allgroupIdStr})"; 
           
            $allGroupInfoStat = Yii::$app->db->createCommand($allGroupInfoStatSql)->queryAll();
            
            if ($allGroupInfoStat) { // 处理相关信息
                foreach ($allGroupInfoStat as $allGroupInfoStatK => $allGroupInfoStatV) {
                    $allGroupInfoStatDeal[$allGroupInfoStatV['gid']][$allGroupInfoStatV['email_type']] = $allGroupInfoStatV;
                }
            }
        }
        
        $channelArr = [2 => 'emarsys', 4 => 'cheet', 6 => 'emarsys_new', 5 => 'benchmark', 9 => 'webpower'];
        $emailMarket = new EmailMarket();
        // 分组信息数据处理
        foreach ($groupInfo['groupList'] as $groupListK => $groupListV) {
            
            // 添加队列时间
            $groupInfo['groupList'][$groupListK]['add_date'] = \yii::$app->bjTime->date("Y-m-d H:i:s",$groupListV['add_date']);
            
            // 开始发送时间
            if ($groupListV['start_time']) {
                $groupInfo['groupList'][$groupListK]['start_time'] = \yii::$app->bjTime->date("Y-m-d H:i:s",$groupListV['start_time']);
            } else {
                $groupInfo['groupList'][$groupListK]['start_time'] = '--';
            }
            
            // 最后一次发送时间
            if ($groupListV['group_last_send']) {
                $groupInfo['groupList'][$groupListK]['group_last_send'] = \yii::$app->bjTime->date("Y-m-d H:i:s",$groupListV['group_last_send']);
            } else {
                $groupInfo['groupList'][$groupListK]['group_last_send'] = '--';
            }
            
            // 成功送达率
            if ($groupListV['channel_id'] == 2 || $groupListV['channel_id'] == 6) {
                $groupListV['send_status_ok_count'] = $groupListV['send_ok_count'] - $groupListV['send_status_fail_count'];
                $groupInfo['groupList'][$groupListK]['send_status_ok_count'] = $groupListV['send_status_ok_count'];
            }
            
            if(empty($groupListV['total_count']))
            {
                $groupInfo['groupList'][$groupListK]['send_status_ok_rate'] =0;
            }else {
                $groupInfo['groupList'][$groupListK]['send_status_ok_rate'] = number_format( $groupListV['send_status_ok_count'] / $groupListV['total_count'] , 4)*100;
            }
           
            // 成功送达率详情
            // $groupInfo['groupList'][$groupListK]['stat']['all_send'] =  
            
            // 打开率点击率相关
            if ($groupListV['send_status_ok_count']) {
                $groupInfo['groupList'][$groupListK]['all_open_rate'] =  number_format($groupListV['open_count'] / $groupListV['send_status_ok_count'],4) * 100;// 总打开率相关数据后面统计
                $groupInfo['groupList'][$groupListK]['click_link_rate'] =  number_format($groupListV['click_link_count'] / $groupListV['send_status_ok_count'],4) * 100;// 总点击率相关数据后面统计
               
            } else {
                $groupInfo['groupList'][$groupListK]['all_open_rate'] = 0;
                $groupInfo['groupList'][$groupListK]['click_link_rate'] = 0;
            }
            //点击转化率
            if($groupListV['open_count']) {
                $groupInfo['groupList'][$groupListK]['click_open_rate'] =  number_format($groupListV['click_link_count'] / $groupListV['open_count'],4) * 100;// 总点击转化率相关数据后面统计
            } else {
                $groupInfo['groupList'][$groupListK]['click_open_rate'] = 0;
            }
            
            // 添加通道名称列
            $groupInfo['groupList'][$groupListK]['channel_name'] = $channelArr[$groupListV['channel_id']];
             
            // 发送方式
            if ($groupListV['send_mode'] == 2) {
                $groupInfo['groupList'][$groupListK]['sendtype'] = '推送';
            } else { // 分天发送
                if ($groupListV['send_type'] == 0) {
                    $groupInfo['groupList'][$groupListK]['sendtype'] = '7天发';
                } else {
                    $groupInfo['groupList'][$groupListK]['sendtype'] = $groupListV['send_type'].'天发';
                }
            }
            
            //网站
            $groupInfo['groupList'][$groupListK]['site_name'] = $siteInfo[$groupListV['site_id']];
            
          
            /* 统计信息相关 ----------start---*/
            $groupInfo['groupList'][$groupListK]['stat'] = [];

            if (isset($allGroupInfoStatDeal) && isset($allGroupInfoStatDeal[$groupListV['group_id']])) {
                $groupInfo['groupList'][$groupListK]['stat']['send_success'] = ""; // 成功送达率提示信息 
                $groupInfo['groupList'][$groupListK]['stat']['open'] = ""; // 打开率提示信息 
                $groupInfo['groupList'][$groupListK]['stat']['click'] = ""; // 点击率提示信息 
                $groupInfo['groupList'][$groupListK]['stat']['click_open'] = ""; // 点击转化率提示信息 
                foreach ($allGroupInfoStatDeal[$groupListV['group_id']] as $allGroupInfoStatDealV) {
                    
                    
                    $emailTypeName =  $emailMarket->getEmailTypeName($allGroupInfoStatDealV['email_type']);
                    if ($groupListV['channel_id'] == 2 || $groupListV['channel_id'] == 6) { // 如果是emarsys通道则送达率为 成功送达率=（发送总数-硬弹-软弹）/发送数*100%即成功送达率=（发送总数-send_fail）/发送数*100%
                        $sendSuccessTemp = $allGroupInfoStatDealV['sent'] - $allGroupInfoStatDealV['send_fail'];
                        if ($sendSuccessTemp < 0) {
                            $sendSuccessTemp = 0;
                        }
                        $sendSuccessRate = $allGroupInfoStatDealV['sent'] == 0 ? 0: number_format($sendSuccessTemp / $allGroupInfoStatDealV['sent'],4)*100;  //成功送达相关
                        $groupInfo['groupList'][$groupListK]['stat']['send_success'] .= '&#13;'.$emailTypeName.":". $sendSuccessTemp.'/'.$allGroupInfoStatDealV['sent']." " . $sendSuccessRate ."%";
                    } elseif ($groupListV['channel_id'] == 4) { // 如果是emarsys通道则送达率为 成功送达率=（send_success）/ 发送数*100%
                        $sendSuccessTemp = $allGroupInfoStatDealV['send_success'];
                        if ($sendSuccessTemp < 0) {
                            $sendSuccessTemp = 0;
                        }
                        $sendSuccessRate = $allGroupInfoStatDealV['sent'] == 0 ? 0: number_format($sendSuccessTemp / $allGroupInfoStatDealV['sent'],4)*100;  //成功送达相关
                        $groupInfo['groupList'][$groupListK]['stat']['send_success'] .= '&#13;'.$emailTypeName.":". $sendSuccessTemp.'/'.$allGroupInfoStatDealV['sent']." " . $sendSuccessRate ."%";
                    }
                    $groupInfo['groupList'][$groupListK]['stat']['send_success'] = trim($groupInfo['groupList'][$groupListK]['stat']['send_success'],'&#13;');
                    if(!isset($sendSuccessTemp)){
                        $sendSuccessTemp = 0;
                    }
                    // 邮件打开率
                    $openRate = $sendSuccessTemp <= 0 ? 0: number_format($allGroupInfoStatDealV['open'] / $sendSuccessTemp,4)*100; // 邮件打开相关
                    $groupInfo['groupList'][$groupListK]['stat']['open'] .= '&#13;'.$emailTypeName.":". $allGroupInfoStatDealV['open'].'/'.$sendSuccessTemp." " . $openRate ."%"; 
                    $groupInfo['groupList'][$groupListK]['stat']['open'] = trim($groupInfo['groupList'][$groupListK]['stat']['open'],'&#13;');
                     
                    // 邮件点击率
                    $clickRate = $sendSuccessTemp <= 0 ? 0: number_format($allGroupInfoStatDealV['click_nums'] / $sendSuccessTemp,4)*100; // 邮件点击相关
                    $groupInfo['groupList'][$groupListK]['stat']['click'] .= '&#13;'.$emailTypeName.":". $allGroupInfoStatDealV['click_nums'].'/' . $sendSuccessTemp ." " . $clickRate ."%"; 
                    $groupInfo['groupList'][$groupListK]['stat']['click'] = trim($groupInfo['groupList'][$groupListK]['stat']['click'],'&#13;');
                    
                    //邮件点击转化率
                    $clickOpenRate = $allGroupInfoStatDealV['open'] <= 0 ? 0 : number_format($allGroupInfoStatDealV['click_nums'] / $allGroupInfoStatDealV['open'],4)*100;
                    $groupInfo['groupList'][$groupListK]['stat']['click_open'] .= '&#13;'.$emailTypeName.":". $allGroupInfoStatDealV['click_nums'].'/' . $allGroupInfoStatDealV['open'] ." " . $clickOpenRate ."%"; 
                    $groupInfo['groupList'][$groupListK]['stat']['click_open'] = trim($groupInfo['groupList'][$groupListK]['stat']['click_open'],'&#13;');
                    
                }
            } else {
                $groupInfo['groupList'][$groupListK]['stat']['send_success'] = ""; // 成功送达率提示信息 
                $groupInfo['groupList'][$groupListK]['stat']['open'] = ""; // 打开率提示信息 
                $groupInfo['groupList'][$groupListK]['stat']['click'] = ""; // 点击率提示信息 
                $groupInfo['groupList'][$groupListK]['stat']['click_open'] = ""; // 点击转化率提示信息 
                $emailMarketTypeAll = $emailMarket->getAllEmailTypeInfo();
                foreach ($emailMarketTypeAll as $emailMarketTypeAllK => $emailMarketTypeAllV) {
                    $groupInfo['groupList'][$groupListK]['stat']['send_success'] .= '&#13;'.$emailMarketTypeAllV['mail_name'].":0/0 0%";
                    $groupInfo['groupList'][$groupListK]['stat']['open'] .= '&#13;'.$emailMarketTypeAllV['mail_name'].":0/0 0%";
                    $groupInfo['groupList'][$groupListK]['stat']['click'] .= '&#13;'.$emailMarketTypeAllV['mail_name'].":0/0 0%";
                    $groupInfo['groupList'][$groupListK]['stat']['click_open'] .= '&#13;'.$emailMarketTypeAllV['mail_name'].":0/0 0%";
                }
                   
            } 
            /* 统计信息相关 ----------end---*/
            // 模版标题相关
            $groupInfo['groupList'][$groupListK]['template_subject_brief'] = substr($groupListV['template_subject'],0,45);

            // 当前状态相关
            if ($groupListV['state'] == 0 && $groupListV['boot_time'] > 0) { // 暂停
                $groupInfo['groupList'][$groupListK]['curState'] = '暂停'; 
            } elseif ($groupListV['state'] == 0 && $groupListV['boot_time'] == 0) {
                $groupInfo['groupList'][$groupListK]['curState'] = '未发送';
            } elseif ($groupListV['state'] == 1 && $groupListV['group_last_send'] == 0) {
                $groupInfo['groupList'][$groupListK]['curState'] = '未发送';
            } elseif ($groupListV['state'] == 1 && $groupListV['group_last_send'] > 0) { // 发送中
                $groupInfo['groupList'][$groupListK]['curState'] = '发送中'; 
            } elseif ($groupListV['state'] == 1 && $groupListV['start_time'] > $curTime) { // 发送中
                $groupInfo['groupList'][$groupListK]['curState'] = '启动'; 
            } elseif ($groupListV['state'] == 2) {
                $groupInfo['groupList'][$groupListK]['curState'] = '已发送'; 
            }
            
            // 是否超限相关
            if (!empty($groupInfo['groupList'][$groupListK]['error_code']) && in_array($groupInfo['groupList'][$groupListK]['error_code'],$this->errorCode)) {
                $groupInfo['groupList'][$groupListK]['is_overrun'] = 1;
            }
            
            
        }
      
        $totalCount = $groupInfo['totalCount'];
        
        
        // 分页相关
        $pages = new Pagination(['totalCount' =>$totalCount, 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);

       return $this->render('//marketing//trigger-mail-monitor-manage/exception-group-list',[
                'data' => $groupInfo['groupList'], 
                'site' => $site,
                'formData' => $formData,
                'pages' => $pages,
            ]);
    }
    
    
    /*
     * 添加用户和网站对应关系数据
     * @return json
     */
    public function actionAddUsersPerSite() {
        $mothod = strtolower(Yii::$app->request->getMethod());
        $userIds = Yii::$app->request->$mothod('user_ids');
        $siteId = Yii::$app->request->$mothod('site_id');
        if(!$siteId) {
             return $this->sysMsg('警告', '站点id不存在!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ], 1);
        }
        
        if(!$userIds) {
            return $this->sysMsg('警告', '未选择用户或用户参数不正确!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ], 1);
        }
        
        $data = [
            'site_id' => $siteId,
            'getter'  => $userIds
        ];
        $SiteMonitorMesGetterModel = new SiteMonitorMessageGetter;
        if($SiteMonitorMesGetterModel->getDataBySiteId($siteId)) {
            $res = $SiteMonitorMesGetterModel->edit($siteId, $data);
        } else {
            $res = $SiteMonitorMesGetterModel->add($data);
        }
        
        return $this->sysMsg('', '操作成功!',$params = [ 'type' => 'success', 'links' => [ ['name'=>'返回主页面' , 'url'=>'/marketing/trigger-mail-monitor-manage/msg-getters-list?site=marketing_email&site_id='.$siteId] ] ] ,1);
         
    }
    
  /*
   * 删除用户
   * @return json
   */
    public function actionDelUsers() {
        $returnData = [];
        $mothod = strtolower(Yii::$app->request->getMethod());
        $userId = Yii::$app->request->$mothod('userId');
        $userId = intval($userId);
        if(!$userId) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "用户信息不存在！";
            echo json_encode($returnData);
            exit;
        }
        $monitorMesGetterModel = new MonitorMessageGetter;
        if($monitorMesGetterModel->delUser($userId)) {
            $returnData['status'] = 0;
            $returnData['errorInfo'] = "success!";
            
        } else {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "删除失败!";
        }
        echo json_encode($returnData);
        exit;
    }
    /*
     * 添加用户
     * @return json
     */
    public function actionAddUsers() {
        $returnData = [];
        $mothod = strtolower(Yii::$app->request->getMethod());
        $userName = Yii::$app->request->$mothod('linkman_username');
        $userName = $userName ? trim($userName) : '';
        $wechart = Yii::$app->request->$mothod('linkman_nickname');
        $wechart = $wechart ? trim($wechart) : '';
        $email = Yii::$app->request->$mothod('linkman_email');
        $email = $email ? trim($email) : '';
        $iphone = Yii::$app->request->$mothod('linkman_phone');
        $iphone = $iphone ? trim($iphone) : '';
        
        // 进行参数过滤
        if(!$userName) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "用户名不能为空!";
            echo json_encode($returnData);
            exit;
        }
        if(!$wechart && !$email && !$iphone) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "联系人信息至少填写一项!";
            echo json_encode($returnData);
            exit;
        }
        
        $emailObj = new EmailMarket();
        if($email && !$emailObj->isEmail($email)) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "邮箱格式不正确!";
            echo json_encode($returnData);
            exit;
        }
        
        $addData = [
            'user_name' => $userName,
            'wechart'   => $wechart,
            'email'     => $email,
            'iphone'    => $iphone,
            'updater'   => Yii::$app->session['admin_info']['real_name']
        ];
        $monitorMesGetterModel = new MonitorMessageGetter;
        if($monitorMesGetterModel ->getUserByUserName($userName)) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "该用户名已经存在!";
            echo json_encode($returnData);
            exit;
        }
        if($monitorMesGetterModel->addUser($addData)) {
            $returnData['status'] = 0;
            $returnData['errorInfo'] = "successs!";
            
        } else {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "添加用户失败!";
            
        }
        echo json_encode($returnData);
        exit;
    }
    
    
     /*
     * 修改用户
     * @return json
     */
    public function actionEditUsers() {
        $returnData = [];
        $mothod = strtolower(Yii::$app->request->getMethod());
        $userName = Yii::$app->request->$mothod('linkman_username');
        $userName = $userName ? trim($userName) : '';
        $wechart = Yii::$app->request->$mothod('linkman_nickname');
        $wechart = $wechart ? trim($wechart) : '';
        $email = Yii::$app->request->$mothod('linkman_email');
        $email = $email ? trim($email) : '';
        $iphone = Yii::$app->request->$mothod('linkman_phone');
        $iphone = $iphone ? trim($iphone) : '';
        $userId = Yii::$app->request->$mothod('user_id');
        $userId = $userId ? intval($userId) : 0;
        // 进行参数过滤
        if(!$userId) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "用户ID不存在!";
            echo json_encode($returnData);
            exit;
        }
        if(!$userName) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "用户名不能为空!";
            echo json_encode($returnData);
            exit;
        }
        if(!$wechart && !$email && !$iphone) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "联系人信息至少填写一项!";
            echo json_encode($returnData);
            exit;
        }
        
        $emailObj = new EmailMarket();
        if($email && !$emailObj->isEmail($email)) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "邮箱格式不正确!";
            echo json_encode($returnData);
            exit;
        }
        
        $editData = [
            'user_name' => $userName,
            'wechart'   => $wechart,
            'email'     => $email,
            'iphone'    => $iphone,
            'updater'   => Yii::$app->session['admin_info']['real_name']
        ];
        $monitorMesGetterModel = new MonitorMessageGetter;
        if($monitorMesGetterModel ->getUserByUserName($userName,$userId)) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "该用户名已经存在!";
            echo json_encode($returnData);
            exit;
        }
        if($monitorMesGetterModel->editUser($userId,$editData)) {
            $returnData['status'] = 0;
            $returnData['errorInfo'] = "successs!";
            
        } else {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "编辑用户失败!";
            
        }
        echo json_encode($returnData);
        exit;
    }
    
    /*
     *消息中心 
     */
    public function actionExceptionMessageCenter()
    {
        $data = [];
        return $this->render('//marketing//trigger-mail-monitor-manage/exception-message-center',[
            'data' => $data, 
        ]);
    }
    
    /**
     * 触发邮件监控列表页面（异常消息列表）
     */
    public function actionExceptionMessageList()
    {
        $data = [];
        $siteInfo = [];
        
        $defaultPageSize = 20;
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
         // 查询网站相关的数据
        $formData = Yii::$app->request->$mothod();
        // 当前用户所有有权限的站点
        $siteInfo_tmp = Yii::$app->authority->getMarketEmailAccessSite();
        $siteInfo[0] = "全部";
        $authSiteIds = array();
        if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
            foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
                $authSiteIds[] = $siteInfo_tmp_v['site_id'];
            }
        }
        
        if (empty($siteInfo)) {
            exit('你好，你没有任何网站的相关权限');
        }
        // 站点id相关
        $formData['site_id'] = isset($formData['site_id']) ? $formData['site_id'] : 0;
        // 获取模版类型
        $TemplateMarket = new TemplateMarket();
        if (!empty($formData['site_id'])) {
            $templateTypeArr = $TemplateMarket->getTemplateType($formData['site_id']);
        } else {
            $templateTypeArr = $TemplateMarket->getTemplateType();
        }
        
        $templateTypeArrInfo = [];
        $templateTypeArrCompaign = [];
        $formData['tempType'] = [];
        //$formData['temp_type_id'] = 0;
        $templateTypeArrInfo[0] = "全部";
        if (isset($templateTypeArr) && is_array($templateTypeArr)) {
            foreach ($templateTypeArr as $templateTypeArrK => $templateTypeArrV) {
                $templateTypeArrInfo[$templateTypeArrV['id']] = $templateTypeArrV['template_type_name'];
            } 
            //$formData['temp_type_id'] = $templateTypeArr[0]['id'];
            $formData['tempType'] = $templateTypeArrInfo;
        }
        $formData['siteInfo'] = $siteInfo;
        $sessionAllowWeb  = Yii::$app->session['admin_info']['allow_web'];
       
        $formData['temp_type_id'] = isset($formData['temp_type_id']) ? intval($formData['temp_type_id']) : 0;
        $formData['type_id'] = $formData['temp_type_id'];
        $formData['exception_type'] = isset($formData['exception_type']) ? intval($formData['exception_type']) : 1;
        
         // 默认的时间数据
        if (!empty($formData['reservation_time'])){
            $reservationTimeArr = explode(' - ',$formData['reservation_time']);
            $formData['startTime'] = $reservationTimeArr[0];
            $formData['endTime'] = $reservationTimeArr[1];
        }
        $curTime = \yii::$app->bjTime->time();
        $timeYearMonthStart = \yii::$app->bjTime->date('Y-m-d',$curTime-30*24*60*60);
        $timeYearMonthCurrent = \yii::$app->bjTime->date('Y-m-d',$curTime);
        $formData['startTime'] = !empty($formData['startTime']) ? $formData['startTime'] : $timeYearMonthStart;
        $formData['endTime'] = !empty($formData['endTime']) ? $formData['endTime'] : $timeYearMonthCurrent;
        
        $formData['site_ids'] = $sessionAllowWeb == 'all' ? 0 : $authSiteIds;
         // 分页参数相关
        $page = Yii::$app->request->$mothod('page') ? Yii::$app->request->$mothod('page') : 1;
        $pageSize = Yii::$app->request->$mothod('pagesize') ? Yii::$app->request->$mothod('pagesize') : $defaultPageSize;
        
        $formData['page'] = $page;
        $formData['pageSize'] = $pageSize;
        
        $mailAutoCreateExceptionMessage = new MailAutoCreateExceptionMessage();
        $dataSelect = $mailAutoCreateExceptionMessage->getExceptionMessage($formData);
        $totalCount = $dataSelect['totalCount'];
        
         // 分页相关
        $pages = new Pagination(['totalCount' =>$totalCount, 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);
        
        if (!empty($dataSelect['exceptionMessage'])) {
            foreach ($dataSelect['exceptionMessage'] as $exceptionMessageKey=>$exceptionMessageVal) {
                $siteName = isset(Yii::$app->params['sites']['marketing_email']['web_index'][$exceptionMessageVal['site_id']]) ? Yii::$app->params['sites']['marketing_email']['web_index'][$exceptionMessageVal['site_id']] : "";
                $siteBriefCode = isset(Yii::$app->params['sites']['marketing_email']['web_config'][$siteName]['brief_code']) ? Yii::$app->params['sites']['marketing_email']['web_config'][$siteName]['brief_code'] : "";
                $dataSelect['exceptionMessage'][$exceptionMessageKey]['site_name'] = $siteName;
                $dataSelect['exceptionMessage'][$exceptionMessageKey]['template_id_name'] = $siteBriefCode . $exceptionMessageVal['template_id'];
                $dataSelect['exceptionMessage'][$exceptionMessageKey]['exception_day']  = yii::$app->bjTime->date('Y-m-d',$exceptionMessageVal['add_time']-24*3600);
                if ($exceptionMessageVal['exception_type'] == 1) {
                    $dataSelect['exceptionMessage'][$exceptionMessageKey]['exception_type_name'] = "推送异常";
                } else {
                    $dataSelect['exceptionMessage'][$exceptionMessageKey]['exception_type_name'] = "发送异常";
                }
                $dataSelect['exceptionMessage'][$exceptionMessageKey]['first_push_time'] = !empty($exceptionMessageVal['first_push_time']) 
                        ? yii::$app->bjTime->date('Y-m-d H:i:s',$exceptionMessageVal['first_push_time']) : "--";
                $dataSelect['exceptionMessage'][$exceptionMessageKey]['last_push_time'] = !empty($exceptionMessageVal['last_push_time']) 
                        ? yii::$app->bjTime->date('Y-m-d H:i:s',$exceptionMessageVal['last_push_time']) : "--";
                $dataSelect['exceptionMessage'][$exceptionMessageKey]['mail_send_time'] = !empty($exceptionMessageVal['mail_send_time']) 
                        ? yii::$app->bjTime->date('Y-m-d H:i:s',$exceptionMessageVal['mail_send_time']) : "--";
                $dataSelect['exceptionMessage'][$exceptionMessageKey]['plan_send_time'] = \yii::$app->bjTime->date('Y-m-d H:i:s',
                       $exceptionMessageVal['plan_send_time']);
                
                if ($exceptionMessageVal['is_push_too_many'] == 1) { // 推送过多
                    if ($exceptionMessageVal['threshold_nums']) {
                        $dataSelect['exceptionMessage'][$exceptionMessageKey]['moreThanThresholdPercent'] = 
                            number_format((($exceptionMessageVal['push_user_count'] - $exceptionMessageVal['threshold_nums']) / $exceptionMessageVal['threshold_nums']) * 100,2);
                    } else {
                        $dataSelect['exceptionMessage'][$exceptionMessageKey]['moreThanThresholdPercent'] = 0;
                    }
                } elseif ($exceptionMessageVal['is_push_too_little'] == 1) {   // 推送过少
                    if ($exceptionMessageVal['threshold_nums']) {
                        $dataSelect['exceptionMessage'][$exceptionMessageKey]['lessThanThresholdPercent'] = 
                            number_format((($exceptionMessageVal['threshold_nums']-$exceptionMessageVal['push_user_count']) / $exceptionMessageVal['threshold_nums']) * 100,2);
                    } else {
                        $dataSelect['exceptionMessage'][$exceptionMessageKey]['lessThanThresholdPercent'] = 0;
                    }
                    
                }
            }
        }
       
        return $this->render('//marketing//trigger-mail-monitor-manage/exception-message-list',[
            'data' => $dataSelect['exceptionMessage'], 
            'formData' => $formData,
            'site' => $site,
            'pages' => $pages,
        ]);
    }
    
    /**
     * 数据同步监控列表页面
     */
    public function actionDataSynMonitorList()
    {
        $data = [];
        $siteInfo = [];

        $defaultPageSize = 20;
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
         // 查询网站相关的数据
        $formData = Yii::$app->request->$mothod();
        // 当前用户所有有权限的站点
        $siteInfo_tmp = Yii::$app->authority->getMarketEmailAccessSite();
//        $siteInfo[0] = "全部";
        $authSiteIds = array();
        if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
            foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
                $authSiteIds[] = $siteInfo_tmp_v['site_id'];
            }
        }

        if (empty($siteInfo)) {
            exit('你好，你没有任何网站的相关权限');
        }
        // 站点id相关
        $formData['site_id'] = isset($formData['site_id']) ? $formData['site_id'] : 0;

        $formData['siteInfo'] = $siteInfo;
//        $formData['siteInfo'] = array_merge($formData['siteInfo'],$this->channelInfo);
        $sessionAllowWeb  = Yii::$app->session['admin_info']['allow_web'];

        $formData['data_source'] = isset($formData['data_source']) ? trim($formData['data_source']) : '';
        $formData['monitor_type'] = isset($formData['monitor_type']) ? intval($formData['monitor_type']) : 0;

         // 默认的时间数据
        if (!empty($formData['reservation_time'])){
            $reservationTimeArr = explode(' - ',$formData['reservation_time']);
            $formData['startTime'] = $reservationTimeArr[0];
            $formData['endTime'] = $reservationTimeArr[1];
        }
        $curTime = \yii::$app->bjTime->time();
        $timeYearMonthStart = \yii::$app->bjTime->date('Y-m-d',$curTime-30*24*60*60);
        $timeYearMonthCurrent = \yii::$app->bjTime->date('Y-m-d',$curTime);
        $formData['startTime'] = !empty($formData['startTime']) ? $formData['startTime'] : $timeYearMonthStart;
        $formData['endTime'] = !empty($formData['endTime']) ? $formData['endTime'] : $timeYearMonthCurrent;

        $formData['site_ids'] = $sessionAllowWeb == 'all' ? 0 : $authSiteIds;
         // 分页参数相关
        $page = Yii::$app->request->$mothod('page') ? Yii::$app->request->$mothod('page') : 1;
        $pageSize = Yii::$app->request->$mothod('pagesize') ? Yii::$app->request->$mothod('pagesize') : $defaultPageSize;

        $formData['page'] = $page;
        $formData['pageSize'] = $pageSize;
//        var_dump($formData);exit;
        $mailAutoCreateExceptionMessage = new MailAutoCreateExceptionMessage();
        $dataSelect = $mailAutoCreateExceptionMessage->getDataSynMonitor($formData);
        $totalCount = $dataSelect['totalCount'];

         // 分页相关
        $pages = new Pagination(['totalCount' =>$totalCount, 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);

        if (!empty($dataSelect['exceptionMessage'])) {
            foreach ($dataSelect['exceptionMessage'] as $exceptionMessageKey=>$exceptionMessageVal) {


                if ($exceptionMessageVal['monitor_type'] == 1) {
                    $dataSelect['exceptionMessage'][$exceptionMessageKey]['monitor_type'] = "数据请求监控";
                } else if($exceptionMessageVal['monitor_type'] == 2) {
                    $dataSelect['exceptionMessage'][$exceptionMessageKey]['monitor_type'] = "数据解压监控";
                } else if($exceptionMessageVal['monitor_type'] == 3) {
                    $dataSelect['exceptionMessage'][$exceptionMessageKey]['monitor_type'] = "数据写入监控";
                } else if($exceptionMessageVal['monitor_type'] == 4) {
                    $dataSelect['exceptionMessage'][$exceptionMessageKey]['monitor_type'] = "同步数据量监控";
                }
                $dataSelect['exceptionMessage'][$exceptionMessageKey]['add_date'] = !empty($exceptionMessageVal['add_time'])
                        ? yii::$app->bjTime->date('Y-m-d H:i:s',$exceptionMessageVal['add_time']) : "--";

                $siteName = isset(Yii::$app->params['sites']['marketing_email']['web_index'][$exceptionMessageVal['site_id']]) ? Yii::$app->params['sites']['marketing_email']['web_index'][$exceptionMessageVal['site_id']] : "";

                if($exceptionMessageVal['monitor_type'] == 3) {
                    if($exceptionMessageVal['source_type'] == 1) {
                        $dataSelect['exceptionMessage'][$exceptionMessageKey]['errorMsg'] = '';
                        if($exceptionMessageVal['error_msg']) {
                            $exceptionMessageVal['error_msg'] = json_decode($exceptionMessageVal['error_msg'], true);
                            foreach($exceptionMessageVal['error_msg'] as $error_msg) {
                                $dataSelect['exceptionMessage'][$exceptionMessageKey]['errorMsg'] .= "用户邮箱".$error_msg['email']."写入数据可失败，失败原因：".$error_msg['reason'].'<br/>';
                            }
                        }
                    }

                }


            }
        }

        return $this->render('//marketing//trigger-mail-monitor-manage/data-sync-monitor-list',[
            'data' => $dataSelect['exceptionMessage'],
            'formData' => $formData,
            'site' => $site,
            'pages' => $pages,
        ]);
    }

    /*
     * 获取指定id的异常监控配置
     */
    public function actionGetSiteSendUsersConfigInfoById()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        $id = Yii::$app->request->$mothod('id');
        $monitorType = Yii::$app->request->$mothod('monitor_type');
        $id = $id ? intval($id) : 0;
        $monitorType = $monitorType ? intval($monitorType) : 0;
        if(!$id) {
            $this->returnJson(10008, "参数不存在！");
        }

        $mailAutoCreateMonitor = new MailAutoCreateMonitor();
        $monitorInfo = $mailAutoCreateMonitor->getSiteSendUsersConfigInfoById($monitorType, $id);
        $this->returnJson(0, "success", $monitorInfo);
    }

    /**
     * 数据同步日志列表页面
     */
    public function actionDataSynLogsList()
    {
        $data = [];
        $siteInfo = [];
        Yii::$app->params['now_addr'] = "系统业务日志";

        $defaultPageSize = 20;
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        // 查询网站相关的数据
        $formData = Yii::$app->request->$mothod();
        // 当前用户所有有权限的站点
        $siteInfo_tmp = Yii::$app->authority->getMarketEmailAccessSite();
        $siteInfo[0] = "全部";
        $authSiteIds = array();
        if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
            foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
                $authSiteIds[] = $siteInfo_tmp_v['site_id'];
            }
        }

        if (empty($siteInfo)) {
            exit('你好，你没有任何网站的相关权限');
        }
        // 站点id相关
        $formData['site_id'] = isset($formData['site_id']) ? $formData['site_id'] : 0;
        $formData['type'] = isset($formData['type']) ? $formData['type'] : 2;

        $formData['siteInfo'] = $siteInfo;
        $sessionAllowWeb  = Yii::$app->session['admin_info']['allow_web'];

        $formData['sync_state'] = isset($formData['sync_state']) ? intval($formData['sync_state']) : 0;

        // 默认的时间数据
        if (!empty($formData['reservation_time'])){
            $reservationTimeArr = explode(' - ',$formData['reservation_time']);
            $formData['startTime'] = $reservationTimeArr[0];
            $formData['endTime'] = $reservationTimeArr[1];
        }
        $curTime = \yii::$app->bjTime->time();
        $timeYearMonthStart = \yii::$app->bjTime->date('Y-m-d',$curTime-30*24*60*60);
        $timeYearMonthCurrent = \yii::$app->bjTime->date('Y-m-d',$curTime);
        $formData['startTime'] = !empty($formData['startTime']) ? $formData['startTime'] : $timeYearMonthStart;
        $formData['endTime'] = !empty($formData['endTime']) ? $formData['endTime'] : $timeYearMonthCurrent;

        $formData['site_ids'] = $sessionAllowWeb == 'all' ? 0 : $authSiteIds;
        // 分页参数相关
        $page = Yii::$app->request->$mothod('page') ? Yii::$app->request->$mothod('page') : 1;
        $pageSize = Yii::$app->request->$mothod('pagesize') ? Yii::$app->request->$mothod('pagesize') : $defaultPageSize;

        $formData['page'] = $page;
        $formData['pageSize'] = $pageSize;

        $mailAutoCreateExceptionMessage = new MailAutoCreateExceptionMessage();
        $dataSelect = $mailAutoCreateExceptionMessage->getDataSynLogs($formData);
        $totalCount = $dataSelect['totalCount'];

        // 分页相关
        $pages = new Pagination(['totalCount' =>$totalCount, 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);

        if (!empty($dataSelect['exceptionMessage'])) {
            foreach ($dataSelect['exceptionMessage'] as $exceptionMessageKey=>$exceptionMessageVal) {
                $siteName = isset(Yii::$app->params['sites']['marketing_email']['web_index'][$exceptionMessageVal['site_id']]) ? Yii::$app->params['sites']['marketing_email']['web_index'][$exceptionMessageVal['site_id']] : "";

                $dataSelect['exceptionMessage'][$exceptionMessageKey]['site_name'] = $siteName;
                if ($exceptionMessageVal['sync_state'] == 1) {
                    $dataSelect['exceptionMessage'][$exceptionMessageKey]['sync_state'] = "正常同步";
                } else if($exceptionMessageVal['sync_state'] == 2) {
                    $dataSelect['exceptionMessage'][$exceptionMessageKey]['sync_state'] = "少同步";
                } else if($exceptionMessageVal['sync_state'] == 3) {
                    $dataSelect['exceptionMessage'][$exceptionMessageKey]['sync_state'] = "未同步";
                } else {
                    $dataSelect['exceptionMessage'][$exceptionMessageKey]['sync_state'] = "未同步";
                }
                $dataSelect['exceptionMessage'][$exceptionMessageKey]['sync_date'] = !empty($exceptionMessageVal['sync_time'])
                    ? yii::$app->bjTime->date('Y-m-d',$exceptionMessageVal['sync_time']) : "--";
                $dataSelect['exceptionMessage'][$exceptionMessageKey]['sync_ok_time'] = !empty($exceptionMessageVal['sync_time'])
                    ? yii::$app->bjTime->date('Y-m-d H:i:s',$exceptionMessageVal['sync_time']) : "--";

            }
        }

        return $this->render('//marketing//trigger-mail-monitor-manage/data-sync-logs-list',[
            'data' => $dataSelect['exceptionMessage'],
            'formData' => $formData,
            'site' => $site,
            'pages' => $pages,
        ]);
    }

    /*
     * 每天四点以后每隔一小时监控crm是否推当天的gb购物车数据
     * @liugang 2018-6-29
     */
    public function actionMonitorCrmToSoaEocartData()
    {
        set_time_limit(0);
        $curDate = \yii::$app->bjTime->date('Y-m-d');
        $curDayStart = \yii::$app->bjTime->strtotime($curDate." 00:00:00");
        
        $count = yii::$app->db->createCommand("SELECT count(*) num from emp_gearbest_email_cart where etl_date > $curDayStart")->queryScalar();
        if($count == 0) {
            $msgCenter = new MsgCenter();
            $dealData['site_id'] = 99; // 发送人员为EMP所属人员
            $dealData['title'] = "【EMP】异常提示【gearbest站购物车邮件大数据未推数】";
            $dealData['exceptionEmailTemplateContent'] = "【EMP】异常提示【gearbest站购物车邮件大数据未推数】：EMP营销邮件，截止当前时间{".\yii::$app->bjTime->date('Y-m-d H:i:s')."}，gearbest站大数据未推送购物车邮件数据。";
            $dealData['exceptionWechatTemplateContent'] = $dealData['exceptionEmailTemplateContent'];
            $msgCenter->go_msgcenter($dealData); 
        }
    }
    
    
    /**
     *  发送异常
     */
    public function actionMonitorSendException()
    {
        set_time_limit(0);
        $mailAutoCreate = new MailAutoCreate();
            
        // 查询所有未删除的并且启动自动触发邮件任务
        $mailAutoCreateList = $mailAutoCreate->getAllAutoCreateListSuitException();
        //取出所有配置的模板id
        $templateIds = $tempTrack = array();
        foreach($mailAutoCreateList as $list)
        {
            $templateIds[] = $list['template_id'];
        }
        
        if($templateIds)
        {
            $templateInfoArr =  yii::$app->db->createCommand("select template_id,id,track_code from mail_template where template_id in(".implode(',',$templateIds).") and is_use = 1 and is_del = 0 and status=1 and is_ab_test = 0")->queryAll();
            foreach($templateInfoArr as $templateInfo)
            {
                $newTrackCode = '';
                $trackCode = explode('_',$templateInfo['track_code']);
                if(isset($trackCode[0]) && isset($trackCode[1]))
                {
                    $newTrackCode = $trackCode[0].'_'.$trackCode[1];
                }
                $tempTrack[$templateInfo['template_id']] = $newTrackCode;
            }
        }

        $userGoods = new UserGoods();
        $mailAutoCreateExceptionMessage = new MailAutoCreateExceptionMessage();
        
        $idsArr = [];
        foreach ($mailAutoCreateList as $key=>$webMailInfo) {
            $webName = Yii::$app->params['sites']['marketing_email']['web_index'][$webMailInfo['site_id']];
            $webMailInfo['auto_create_id'] = $webMailInfo['id'];
            $curBjTime = \yii::$app->bjTime->time();
            $curDate = \yii::$app->bjTime->date('Y-m-d');
            $curDayStart = \yii::$app->bjTime->strtotime($curDate." 00:00:00");
            
            $data = [];
            $data['module_name'] = "marketing_email";
            // 各种邮件的处理
            // 查看是否到已经添加队列的时间
            $hours = 3600;
            
            if($webMailInfo['plan_send_time'] + $hours > 23*60*60) {
                $curDayStart = $curDayStart - 24*60*60;
            }
                
            $planSendTime = $curDayStart + $webMailInfo['plan_send_time'];
            
            if ($curBjTime - $curDayStart >= $webMailInfo['plan_send_time'] + $hours) {  // 生成分组之后1个小时
                // 保存扫描过的id信息
                $idsArr[] = $webMailInfo['id'];
                //查看分组表中有没有生成分组
                $whereArr = array(
                    'group_name' => $tempTrack[$webMailInfo['template_id']],
                    'start_time' => $curDayStart + $webMailInfo['plan_send_time'],
                    'is_auto_group' => 1
                );
                $groupModel = new MailGroup();
                if(!$groupModel->isExsitGroupByCondition($whereArr)) {
                    
                    // 异常信息保存
                    $exceptionInfo = [];

                    // 获取发送用户量，推送用户量，过期用户量，过滤用户量
                    // 推送用户量（当天北京时间00:00:00到监控时间点总推送用户量）
                    $exceptionInfo['push_user_count'] = $userGoods->getNumsByTime($webMailInfo['site_id'], $curDayStart-1,$curBjTime ,$webMailInfo);
                    
                    // 发送用户量
                    $exceptionInfo['send_user_count'] = 0;
                    
                    // 过期用户量
                    $exceptionInfo['expire_user_count'] = 0;
                    
                    // 到计划任务时间点之前24小时推送的用户量
                    $addGroupTime24HourBeforePushUserCount = $userGoods->getNumsByTime($webMailInfo['site_id'], $planSendTime-24*3600,$planSendTime,$webMailInfo);
                    
                    // 过滤用户量
                    $exceptionInfo['filter_count'] =  $addGroupTime24HourBeforePushUserCount;
                    
                    // 推送完成时间
                    $exceptionInfo['last_push_time'] = 0;
                    $exceptionInfo['exception_type'] = 2; // 代表是发送异常
                   
                    $exceptionInfo['site_id'] = $webMailInfo['site_id'];
                    $exceptionInfo['template_id'] = $webMailInfo['template_id'];
                    
                    // 预计发送时间
                    $exceptionInfo['plan_send_time'] = $planSendTime;
                    $exceptionInfo['threshold_percent'] = 0;
                    
                    $exceptionInfo['is_push_too_many'] = 0;
                    $exceptionInfo['is_push_too_little'] = 0;
                    $exceptionInfo['is_expire_too_many'] = 0;
                    $exceptionInfo['is_practical'] = 1;
                    $exceptionInfo['update_time'] = $exceptionInfo['add_time'] = $curBjTime;
                    $messageId = $mailAutoCreateExceptionMessage->add($exceptionInfo);
                    
                    // 发送邮件和微信信息
                    $msgCenter = new MsgCenter();
                    $msgCenter->sendMessage($exceptionInfo,$messageId);  
                }
            }
        }
        $mailAutoCreate->updateAutoCreateSuitException($idsArr);
    }
    
    /**
     * 推送监控信息生成方法 (0:0:0执行)
     */
    public function actionMonitorPushException()
    {
        // 获取监控项
        $mailAutoCreateMonitor = new MailAutoCreateMonitor();
        $autoCreateMonitorListSuit = $mailAutoCreateMonitor->getAutoCreateMonitorListSuit();
        
        // 异常信息结果数据
        $exceptionInfo = [];
        $curDate = \yii::$app->bjTime->date('Y-m-d');
        $curDayStart = \yii::$app->bjTime->strtotime($curDate." 00:00:00"); // 当天0时0分0秒时间戳
        $curOneDayBeforeStart = $curDayStart - 24*3600; // 前一天0时0分0秒时间戳
        $userGoods = new UserGoods();
        $mailGroup = new MailGroup();
        // 遍历获取相关数据
        foreach ($autoCreateMonitorListSuit as $autoCreateMonitorListSuitVal) {
           
            if (!isset($exceptionInfo[$autoCreateMonitorListSuitVal['template_id']])) {
                $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']] = [];
            }
            $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['site_id'] = $autoCreateMonitorListSuitVal['site_id']; 
            // 前一天触发邮件中配置的发送时间点
            $planSendTime = $curOneDayBeforeStart + $autoCreateMonitorListSuitVal['plan_send_time'];
            $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['plan_send_time'] = $planSendTime;
            
            // 获取北京时间前一天推送总数,推送过期数，最后一条数据推送时间
            if (empty($exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['push_user_count'])) {
                
                // 推送总数
                $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['push_user_count'] = 
                        $userGoods->getNumsByTime($autoCreateMonitorListSuitVal['site_id'], $curOneDayBeforeStart-1, $curDayStart, $autoCreateMonitorListSuitVal);
                
                // 推送过期数量
                $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['expire_user_count'] = 
                        $userGoods->getNumsByTime($autoCreateMonitorListSuitVal['site_id'], $planSendTime, $curDayStart, $autoCreateMonitorListSuitVal);
                
                // 最后一条数据推送时间
                $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['last_push_time'] =
                        $userGoods->getLastOneByTime($autoCreateMonitorListSuitVal['site_id'], $curOneDayBeforeStart-1, $curDayStart, $autoCreateMonitorListSuitVal);
               
                // 最开始一条数据推送时间
                $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['first_push_time'] =
                        $userGoods->getFirstOneByTime($autoCreateMonitorListSuitVal['site_id'], $curOneDayBeforeStart-1, $curDayStart, $autoCreateMonitorListSuitVal);
                
                // 计算生成分组时间
                if ($autoCreateMonitorListSuitVal['send_mode_id'] == 0) { // 说明是网站推送当日发送
                    // 直接从分组表中获取相关分组数量,发送时间取实际发送时间，过滤数发送之前24小时内推送总数-分组数量
                    $currentGroupInfo =  $mailGroup->getGroupInfoByTimeAndTemplateId($curOneDayBeforeStart-1, $curDayStart,$autoCreateMonitorListSuitVal['template_id']);
                    if (!empty($currentGroupInfo)) {
                        $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['send_user_count'] = $currentGroupInfo['total_count'];
                        $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['mail_send_time'] = $currentGroupInfo['add_date'];
                        $addGroupTime24HourBeforePushUserCount = $userGoods->getNumsByTime($autoCreateMonitorListSuitVal['site_id'], $planSendTime-24*3600,$planSendTime,$autoCreateMonitorListSuitVal);
                
                        $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['filter_count'] = $addGroupTime24HourBeforePushUserCount - $currentGroupInfo['total_count']; 
                      
                    } else {
                        $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['send_user_count'] = 0;
                        $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['mail_send_time'] = 0;
                        $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['filter_count'] = 0;  
                    }
                    $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['is_practical'] = 1;
                    $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['update_time'] = $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['add_time'] = \yii::$app->bjTime->time(); 
                } else { // 加入购物车时间延后n天之后发送 先不做
                   
                    /*$exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['send_user_count'] =
                            $userGoods->getNumsByCondition($autoCreateMonitorListSuitVal['site_id'], $curOneDayBeforeStart - 24*3600 + $autoCreateMonitorListSuitVal['plan_send_time'], 
                                    $curOneDayBeforeStart + $autoCreateMonitorListSuitVal['plan_send_time'], $autoCreateMonitorListSuitVal);
                    $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['mail_send_time'] = $curOneDayBeforeStart + $autoCreateMonitorListSuitVal['delay_day'] * 24 * 3600 
                            + $autoCreateMonitorListSuitVal['plan_send_time'];    
                    $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['is_practical'] = 0;*/
                    
                }
            }     
            // 判断数据是否异常
           
            if ($autoCreateMonitorListSuitVal['monitor_type'] == 1) { // 推送过期
                // 如果推送过期数占总数的比例大于阀值（说明是异常信息）
                if ($exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['expire_user_count'] 
                        > $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['push_user_count'] * $autoCreateMonitorListSuitVal['threshold_percent'] / 100 ) {
                    // 推送过期数异常
                    $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['is_expire_too_many'] = 1;
                }
            } elseif ($autoCreateMonitorListSuitVal['monitor_type'] == 2) { // 推送过少
                // 如果推送数少于阀值（说明是异常信息）
                if ($exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['push_user_count'] < $autoCreateMonitorListSuitVal['threshold_nums'] * $autoCreateMonitorListSuitVal['threshold_percent'] / 100 ) {
                    $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['is_push_too_little'] = 1;
                }
                if (!empty($autoCreateMonitorListSuitVal['threshold_percent'])) {
                    $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['threshold_percent_little'] = $autoCreateMonitorListSuitVal['threshold_percent'];
                }
                if (!empty($autoCreateMonitorListSuitVal['threshold_nums'])) {
                    $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['threshold_nums'] = $autoCreateMonitorListSuitVal['threshold_nums'];
                }
            } elseif ($autoCreateMonitorListSuitVal['monitor_type'] == 3) { // 推送过多
                // 如果推送数大于阀值（说明是异常信息）
                if ($exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['push_user_count'] > $autoCreateMonitorListSuitVal['threshold_nums'] * $autoCreateMonitorListSuitVal['threshold_percent'] / 100 ) {
                    $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['is_push_too_many'] = 1;
                }
                if (!empty($autoCreateMonitorListSuitVal['threshold_percent'])) {
                    $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['threshold_percent_many'] = $autoCreateMonitorListSuitVal['threshold_percent'];
                }
                if (!empty($autoCreateMonitorListSuitVal['threshold_nums'])) {
                    $exceptionInfo[$autoCreateMonitorListSuitVal['template_id']]['threshold_nums'] = $autoCreateMonitorListSuitVal['threshold_nums'];
                }
            }
             
        }
        
        
        // 遍历处理相关数据并且过滤掉不是异常的数据
        $exceptionInfoDeal = [];
        $exceptionInfoDealTemp = [];
        $mailAutoCreateExceptionMessage = new MailAutoCreateExceptionMessage();
        $msgCenter = new MsgCenter();
        foreach ($exceptionInfo as $templateId => $exceptionInfoVal) {
            if (empty($exceptionInfoVal['is_push_too_many']) && empty($exceptionInfoVal['is_push_too_little']) && empty($exceptionInfoVal['is_expire_too_many'])) {
                // 说明不是异常信息
                continue;
            } else {
                // 说明是异常信息
                $exceptionInfoDealTemp['is_push_too_many'] = !empty($exceptionInfoVal['is_push_too_many']) ? $exceptionInfoVal['is_push_too_many'] : 0;
                $exceptionInfoDealTemp['is_push_too_little'] = !empty($exceptionInfoVal['is_push_too_little']) ? $exceptionInfoVal['is_push_too_little'] : 0;
                $exceptionInfoDealTemp['is_expire_too_many'] = !empty($exceptionInfoVal['is_expire_too_many']) ? $exceptionInfoVal['is_expire_too_many'] : 0;
                $exceptionInfoDealTemp['template_id'] =  $templateId;
                $exceptionInfoDealTemp['push_user_count'] = $exceptionInfoVal['push_user_count'];
                $exceptionInfoDealTemp['expire_user_count'] = $exceptionInfoVal['expire_user_count'];
                $exceptionInfoDealTemp['last_push_time'] = isset($exceptionInfoVal['last_push_time']['create_time']) ? $exceptionInfoVal['last_push_time']['create_time'] : 0;
                $exceptionInfoDealTemp['first_push_time'] = isset($exceptionInfoVal['first_push_time']['create_time']) ? $exceptionInfoVal['first_push_time']['create_time'] : 0;
                $exceptionInfoDealTemp['send_user_count'] = $exceptionInfoVal['send_user_count'];
                $exceptionInfoDealTemp['mail_send_time'] = $exceptionInfoVal['mail_send_time'];
                $exceptionInfoDealTemp['filter_count'] = $exceptionInfoVal['filter_count'];
                $exceptionInfoDealTemp['is_practical'] = $exceptionInfoVal['is_practical'];
                $exceptionInfoDealTemp['add_time'] = $exceptionInfoVal['add_time'];
                $exceptionInfoDealTemp['update_time'] = $exceptionInfoVal['update_time'];
                $exceptionInfoDealTemp['site_id'] = $exceptionInfoVal['site_id'];
                $exceptionInfoDealTemp['plan_send_time'] = $exceptionInfoVal['plan_send_time'];
                if (!empty($exceptionInfoVal['is_push_too_many'])) {
                    $exceptionInfoDealTemp['threshold_percent'] = !empty($exceptionInfoVal['threshold_percent_many']) ? $exceptionInfoVal['threshold_percent_many'] : 0;
                } elseif (!empty($exceptionInfoVal['is_push_too_little'])) {
                    $exceptionInfoDealTemp['threshold_percent'] = !empty($exceptionInfoVal['threshold_percent_little']) ? $exceptionInfoVal['threshold_percent_little'] : 0;
                }
               
                $exceptionInfoDealTemp['threshold_nums'] = !empty($exceptionInfoVal['threshold_nums']) ? $exceptionInfoVal['threshold_nums'] : 0;
                $exceptionInfoDealTemp['exception_type'] = 1;
                
                // 异常数据入库
                $messageId = $mailAutoCreateExceptionMessage->add($exceptionInfoDealTemp);
                
                // 发送邮件和微信信息
                $msgCenter->sendMessage($exceptionInfoDealTemp,$messageId);
                //$exceptionInfoDeal[] = $exceptionInfoDealTemp;
            } 
        }
        
//        if (!empty($exceptionInfoDeal)) { // 异常数据入库
//            $mailAutoCreateExceptionMessage = new MailAutoCreateExceptionMessage();
//            $mailAutoCreateExceptionMessage->addBatch($exceptionInfoDeal);
//            foreach ($exceptionInfoDeal as $exceptionInfoDealVal) {
//                // 发送邮件和微信信息
//                $msgCenter = new MsgCenter();
//                $msgCenter->sendMessage($exceptionInfoDealVal);
//            }
//        }
    }
   
    /**
     * 添加某一配置项
     */
    public function actionAddMonitorAjax()
    {
        $returnData = [];
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        $formData = Yii::$app->request->$mothod();
        $addData['site_id'] = isset($formData['site_id']) ? intval($formData['site_id']) : 0;
        $addData['template_id'] = isset($formData['template_id']) ? intval($formData['template_id']) : 0;
        $addData['monitor_type'] = isset($formData['monitor_type']) ? intval($formData['monitor_type']) : 0;
        $addData['exception_type'] = isset($formData['exception_type']) ? intval($formData['exception_type']) : 0;
        $addData['monitor_rule'] = isset($formData['monitor_rule']) ? addslashes($formData['monitor_rule']) : '';
        $addData['threshold_nums'] = isset($formData['threshold_nums']) ? intval($formData['threshold_nums']) : 0;
       
        $addData['threshold_percent'] = isset($formData['threshold_percent']) ? number_format($formData['threshold_percent'],2) : 0;
      
        // 数据判断
        $returnData['status'] = 0;
        if (empty($addData['site_id'])) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "传递参数不完整，没有选择网站!";
        }
        
        if (empty($addData['template_id'])) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "传递参数不完整，没有选择相应模板!";
        }
        
        if (empty($addData['monitor_type'])) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "传递参数不完整，没有选择监控类型!";
        }
        
        if (empty($addData['exception_type'])) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "传递参数不完整，没有选择异常类型!";
        }
        
        if (empty($addData['monitor_rule'])) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "传递参数不完整，没有填写监控规则!";
        }
        
        if ($returnData['status']) {
            echo json_encode($returnData);
            exit;
        }
        // 查看当前用户是否有当前网站权限
        $flag = Yii::$app->authority->judgeMarketEmailHaveSite($formData['site_id']);
        if (!$flag) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "您没有相关网站的权限";
            echo json_encode($returnData);
            exit;
        }
        
        // 根据模板id获取模板类型id值
        $mailTemplate = new MailTemplate;
        $tempInfo = $mailTemplate->getTemplateById($addData['template_id']);
        if (empty($tempInfo) || empty($tempInfo['type_id'])) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "当前模板类型不存在或者已经禁用";
            echo json_encode($returnData);
            exit;
        }
        
        $session        = Yii::$app->session;
        $admin_info     = $session['admin_info'];
        $addData['edit_username'] = $admin_info['real_name'];
       
        $mailAutoCreateMonitor = new MailAutoCreateMonitor();
        if (isset($formData['id']) && $formData['id']) { // 代表是编辑
            $mailAutoCreateMonitor->edit(intval($formData['id']),$addData);
        } else {
            // 查看当前邮件模板是否有激活装填的同样的监控项
            $monitorCount = $mailAutoCreateMonitor->getMonitorCount(['template_id'=>$addData['template_id'],'monitor_type'=>$addData['monitor_type'],'exception_type'=>$addData['exception_type']]);
            if ($monitorCount) {
                $returnData['status'] = 1;
                $returnData['errorInfo'] = "当前触发邮件模板已有同样的监控项！";
                echo json_encode($returnData);
                exit;
            } else {
                $mailAutoCreateMonitor->add($addData);
            }
        }
       
        
        $returnData['errorInfo'] = 'success!';
        echo json_encode($returnData);
        exit;
    }
    
    /**
     *  删除某一配置项ajax
     */
    public function actionDelMonitorAjax()
    {
        $returnData = [];
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        $formData = Yii::$app->request->$mothod();
        $formData['id'] = isset($formData['id']) ? intval($formData['id']) : 0;
        if (empty($formData['id'])) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "传递参数不完整!";
            echo json_encode($returnData);
            exit;
        }
        
        // 查看当前配置项属于哪一网站
        $mailAutoCreateMonitor = new MailAutoCreateMonitor();
        $monitorInfo = $mailAutoCreateMonitor->getMonitorInfoById($formData['id']);
        $flag = Yii::$app->authority->judgeMarketEmailHaveSite($monitorInfo['site_id']);
        if (!$flag) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "您没有相关网站的权限";
            echo json_encode($returnData);
            exit;
        }
        
        $session        = Yii::$app->session;
        $admin_info     = $session['admin_info'];
        $addSaid = $admin_info['real_name'];
        
        // 把当前分组的状态置为删除
        $mailAutoCreateMonitor->delMonitorById($formData['id'],$addSaid);
        $returnData['status'] = 0;
        $returnData['errorInfo'] = "success!";
        echo json_encode($returnData);
        exit;  
    }
    
    /**
     * 异步获取某一网站，某一模版id项的监控
     */
    public function actionGetMonitorListAjax()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        $formData = Yii::$app->request->$mothod();
        $returnData=[];
        $formData['site_id'] = isset($formData['site_id']) ? intval($formData['site_id']) : 0;
        $formData['template_id'] = isset($formData['template_id']) ? intval($formData['template_id']) : 0;
        $mailAutoCreate = new MailAutoCreate();
        if (!empty($formData['site_id'])) {
            
            // 查看当前用户是否有相关网站的权限
            $flag = Yii::$app->authority->judgeMarketEmailHaveSite($formData['site_id']);
            if (!$flag) {
                $returnData['status'] = 0;
                $returnData['errorInfo'] = "您没有相关网站的权限";
                $returnData['data'] = [];
                echo json_encode($returnData);
                exit;
            }
            
            $formData['site_name'] = isset(Yii::$app->params['sites']['marketing_email']['web_index'][$formData['site_id']]) ? Yii::$app->params['sites']['marketing_email']['web_index'][$formData['site_id']] : "";
            $siteBriefCode = isset(Yii::$app->params['sites']['marketing_email']['web_config'][$formData['site_name']]['brief_code']) ? Yii::$app->params['sites']['marketing_email']['web_config'][$formData['site_name']]['brief_code'] : "";
            // 查看当前网站的触发邮件信息
            $autoCreateEmailArr = $mailAutoCreate->getAutoCreateBySite($formData['site_id']);
            
            $autoCreateEmailArrDeal = [];
            $autoCreateEmailFirst = 0;
            foreach ($autoCreateEmailArr as $autoCreateEmailArrVal) {
                $autoCreateEmailArrDeal[$autoCreateEmailArrVal['template_id']] = $autoCreateEmailArrVal['template_type_name'] . "(模版ID:{$siteBriefCode}{$autoCreateEmailArrVal['template_id']})";
                if (empty($autoCreateEmailFirst)) {
                    $autoCreateEmailFirst = $autoCreateEmailArrVal['template_id'];
                }
            }
            $returnData['data'] = [];
            $returnData['data']['autoCreateEmail'] = $autoCreateEmailArrDeal;
            if (!empty($autoCreateEmailFirst)) {
                $mailAutoCreateMonitor = new MailAutoCreateMonitor();
                $monitorArr = $mailAutoCreateMonitor->getMonitorListByTemplateId($autoCreateEmailFirst);
                
                // 遍历处理相关数据
                foreach ($monitorArr as $monitorArrKey => $monitorArrVal) {
                    $monitorArr[$monitorArrKey]['monitorId'] = "EM{$siteBriefCode}{$monitorArrVal['id']}"; 
                }
                
                $returnData['data']['monitorData'] = $monitorArr;
            } 
            $returnData['status'] = 0;
            $returnData['errorInfo'] = "success!";
            
        } elseif (!empty($formData['template_id'])) {
            
            // 获取当前模版id对应的网站信息
            $mailTemplate = new MailTemplate;
            $tempInfo = $mailTemplate->getTemplateById($formData['template_id']);
            
            if (empty($tempInfo)) {
                $returnData['status'] = 1;
                $returnData['errorInfo'] = "相关模版不存在!";
                $returnData['data'] = [];
                echo json_encode($returnData);
                exit;
            }
            
            // 判断模版对应的网站是否有权限
            $flag = Yii::$app->authority->judgeMarketEmailHaveSite($tempInfo['site_id']);
            if (!$flag) {
                $returnData['status'] = 1;
                $returnData['errorInfo'] = "您没有相关网站的权限";
                $returnData['data'] = [];
                echo json_encode($returnData);
                exit;
            }
            $siteName = isset(Yii::$app->params['sites']['marketing_email']['web_index'][$tempInfo['site_id']]) ? Yii::$app->params['sites']['marketing_email']['web_index'][$tempInfo['site_id']] : "";
            $siteBriefCode = isset(Yii::$app->params['sites']['marketing_email']['web_config'][$siteName]['brief_code']) ? Yii::$app->params['sites']['marketing_email']['web_config'][$siteName]['brief_code'] : "";
            
            // 查看当前模版对应的监控项
            $mailAutoCreateMonitor = new MailAutoCreateMonitor();
            $monitorArr = $mailAutoCreateMonitor->getMonitorListByTemplateId($formData['template_id']);
            
            // 遍历处理相关数据
            foreach ($monitorArr as $monitorArrKey => $monitorArrVal) {
                $monitorArr[$monitorArrKey]['monitorId'] = "EM{$siteBriefCode}{$monitorArrVal['id']}"; 
            }
            $returnData['data']['monitorData'] = $monitorArr;
            $returnData['status'] = 0;
            $returnData['errorInfo'] = "success!";
        } else {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "传递参数不完整!";
            $returnData['data'] = [];
        }
        
        echo json_encode($returnData);
        exit;
    }
    /**
     * 监控设置-默认
     */
    public function actionList()
    {
        $data = [];
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        $formData = Yii::$app->request->$mothod();
        
        $formData['type'] = isset($formData['type']) ? intval($formData['type']) : 1;

        // 查询有触发邮件相关配置的网站
        $mailAutoCreate = new MailAutoCreate();
        $siteInfoHaveTriggerMail = $mailAutoCreate->getAllSiteHaveAutoCreate();
        
        $siteInfoHaveTriggerArr = [];
        foreach ($siteInfoHaveTriggerMail as $siteInfoHaveTriggerMailVal) {
            $siteInfoHaveTriggerArr[] = $siteInfoHaveTriggerMailVal['site_id'];
        }
        
        // 当前用户所有有权限的站点
        $siteInfo = [];
        $siteInfo_tmp = Yii::$app->authority->getMarketEmailAccessSite();
        $firstSiteId  = 0;
        $firstSiteName = "";
        if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
            foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                if (in_array($siteInfo_tmp_v['site_id'],$siteInfoHaveTriggerArr)) {
                    if (empty($firstSiteId)) {
                        $firstSiteId = $siteInfo_tmp_v['site_id'];
                        $firstSiteName = $siteInfo_tmp_v['name'];
                    }
                    $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
                }
                
            }
        }
        
        $formData['siteInfo'] = $siteInfo;
        // 默认显示第一个有权限的网站的相关信息
        $siteBriefCode = "";
        $formData['site_id'] = isset($formData['site_id']) ? intval($formData['site_id']) : $firstSiteId;
        
        $formData['site_name'] = isset(Yii::$app->params['sites']['marketing_email']['web_index'][$formData['site_id']]) ? Yii::$app->params['sites']['marketing_email']['web_index'][$formData['site_id']] : "";
        $siteBriefCode = isset(Yii::$app->params['sites']['marketing_email']['web_config'][$formData['site_name']]['brief_code']) ? Yii::$app->params['sites']['marketing_email']['web_config'][$formData['site_name']]['brief_code'] : "";
        
       
        // 查看当前网站的触发邮件信息
        $autoCreateEmailArr = $mailAutoCreate->getAutoCreateBySite($formData['site_id']);
        
        // 处理相关数据
        $autoCreateEmailArrDeal = [];
        $autoCreateEmailFirst = 0;
        foreach ($autoCreateEmailArr as $autoCreateEmailArrVal) {
            $autoCreateEmailArrDeal[$autoCreateEmailArrVal['template_id']] = $autoCreateEmailArrVal['template_type_name'] . "(模版ID:{$siteBriefCode}{$autoCreateEmailArrVal['template_id']})";
            if (empty($autoCreateEmailFirst)) {
                $autoCreateEmailFirst = $autoCreateEmailArrVal['template_id'];
            }
        }
        $formData['autoCreateEmailArrDeal'] = $autoCreateEmailArrDeal;
        $formData['template_id'] = isset($formData['template_id']) ? intval($formData['template_id']) : $autoCreateEmailFirst;
        $mailAutoCreateMonitor = new MailAutoCreateMonitor();
        $monitorArr = $mailAutoCreateMonitor->getMonitorListByTemplateId($formData['template_id']);
        
        // 遍历处理相关数据
        foreach ($monitorArr as $monitorArrKey => $monitorArrVal) {
            $monitorArr[$monitorArrKey]['monitorId'] = "EM{$siteBriefCode}{$monitorArrVal['id']}"; 
        }
        $formData['monitorArr'] = $monitorArr;
        
      
        return $this->render('//marketing//trigger-mail-monitor-manage/list',[
            'formData' => $formData,
        ]);    
    }
    
    /*
     * 网站推送用户及获取通道数据异常配置列表
     */
    public function actionDataExceptionList()
    {
        $data = [];
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        $formData = Yii::$app->request->$mothod();
        $monitorType = isset($formData['monitor_type']) ? $formData['monitor_type'] : 1;
        $formData['monitorArr'] = [];

        $mailAutoCreateMonitor = new MailAutoCreateMonitor();
        if($monitorType == 1) { // 网站
            Yii::$app->params['now_addr'] = '监控设置-默认';
            $monitorArr = $mailAutoCreateMonitor->getSiteSendUsersConfigInfo($monitorType);
            foreach($monitorArr as $key => $monitor) {
                $formData['monitorArr'][$key]['site_name'] = isset(Yii::$app->params['sites']['marketing_email']['web_index'][$monitor['site_id']]) ? Yii::$app->params['sites']['marketing_email']['web_index'][$monitor['site_id']] : "";
                $formData['monitorArr'][$key]['register_user_min_nums'] = $monitor['register_user_min_nums'];
                $formData['monitorArr'][$key]['register_user_max_nums'] = $monitor['register_user_max_nums'];
                $formData['monitorArr'][$key]['login_user_min_nums'] = $monitor['login_user_min_nums'];
                $formData['monitorArr'][$key]['login_user_max_nums'] = $monitor['login_user_max_nums'];
                $formData['monitorArr'][$key]['subscribe_user_min_nums'] = $monitor['subscribe_user_min_nums'];
                $formData['monitorArr'][$key]['subscribe_user_max_nums'] = $monitor['subscribe_user_max_nums'];
                $formData['monitorArr'][$key]['order_user_min_nums'] = $monitor['order_user_min_nums'];
                $formData['monitorArr'][$key]['order_user_max_nums'] = $monitor['order_user_max_nums'];
                $formData['monitorArr'][$key]['state'] = $monitor['state'];
                $formData['monitorArr'][$key]['id'] = $monitor['id'];

            }

        } else if($monitorType == 2) { // 发送渠道
            $monitorArr = $mailAutoCreateMonitor->getSiteSendUsersConfigInfo($monitorType);
            foreach($monitorArr as $key => $monitor) {
                $formData['monitorArr'][$key]['channel_name'] = isset($this->channelInfo[$monitor['channel_id']]) ? $this->channelInfo[$monitor['channel_id']] : "";
                $formData['monitorArr'][$key]['state'] = $monitor['state'];
                $formData['monitorArr'][$key]['id'] = $monitor['id'];
            }

        }
        $formData['monitor_type'] = $monitorType;
        return $this->render('//marketing//trigger-mail-monitor-manage/list',[
            'formData' => $formData,
        ]);
    }

    /*
     * 禁用数据异常监控配置
     */
    public function actionStopDataException()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        $formData = Yii::$app->request->$mothod();

        $id = $formData['id'] ? intval($formData['id']) : 0;

        if($id) {
            $mailAutoCreateMonitor = new MailAutoCreateMonitor();
            if($mailAutoCreateMonitor->updateDataExceptionStatus($id,0)){
                $this->returnJson(0, "success");
            }
        }
        $this->returnJson(10008, "操作失败！");
    }

    /*
     * 开启数据异常监控配置
     */
    public function actionStartDataException()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        $formData = Yii::$app->request->$mothod();

        $id = $formData['id'] ? intval($formData['id']) : 0;

        if($id) {
            $mailAutoCreateMonitor = new MailAutoCreateMonitor();
            if($mailAutoCreateMonitor->updateDataExceptionStatus($id,1)){
                $this->returnJson(0, "success");
            }
        }
        $this->returnJson(10008, "操作失败！");
    }
    /*
     * 编辑数据异常监控配置
     */
    public function actionEditDataException()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        $formData = Yii::$app->request->$mothod();

        $id = $formData['id'] ? intval($formData['id']) : 0;
        $updateArr = [];
        if($id) {
            if($formData['register_user_min_nums']) {
                $updateArr['register_user_min_nums'] = intval($formData['register_user_min_nums']);
            }
            if($formData['register_user_max_nums']) {
                $updateArr['register_user_max_nums'] = intval($formData['register_user_max_nums']);
            }
            if($formData['login_user_min_nums']) {
                $updateArr['login_user_min_nums'] = intval($formData['login_user_min_nums']);
            }
            if($formData['login_user_max_nums']) {
                $updateArr['login_user_max_nums'] = intval($formData['login_user_max_nums']);
            }
            if($formData['subscribe_user_min_nums']) {
                $updateArr['subscribe_user_min_nums'] = intval($formData['subscribe_user_min_nums']);
            }
            if($formData['subscribe_user_max_nums']) {
                $updateArr['subscribe_user_max_nums'] = intval($formData['subscribe_user_max_nums']);
            }
            if($formData['order_user_min_nums']) {
                $updateArr['order_user_min_nums'] = intval($formData['order_user_min_nums']);
            }
            if($formData['order_user_max_nums']) {
                $updateArr['order_user_max_nums'] = intval($formData['order_user_max_nums']);
            }

            $mailAutoCreateMonitor = new MailAutoCreateMonitor();
            $mailAutoCreateMonitor->updateDataException($id,$updateArr);
            $this->returnJson(0, "success");

        }
        $this->returnJson(10008, "操作失败！");
    }
    /**
     * 监控设置-编辑
     */
    public function actionEdit()
    {        
        $data = [];
        return $this->render('//marketing//trigger-mail-monitor-manage/edit',[
            'data' => $data, 
        ]);    
    }
}